import {
  LockOutlined,
  LogoutOutlined,
  RightOutlined,
  UserOutlined,
  SettingOutlined,
  BellOutlined,
} from '@ant-design/icons';
import { message, Modal, Popover, Button, Descriptions, Badge, Space, Drawer, List } from 'antd';
import { FormInstance } from 'antd/lib/form';
import React from 'react';
import {
  casLogout,
  getCasMessages,
  getCasMessagesPoll,
  modifyCasUserPwd,
  readCasMessages,
} from 'admin/servers/servers';
import './style.scss';
import { JSONObject } from 'admin/schema/common';
import {
  setLoginInfo,
  setToken,
  setUserInfo,
  setUserInfoLater,
  setCheckInState,
  setUaConfig,
  setAddTaskFormData,
} from 'store/root/action';
import { connect } from 'react-redux';
import ResetPassword from 'admin/components/ResetPassword';
import moment from 'moment';
import { showWebSenstive, webSenstiveMask } from 'utils/tools';
import { logoutSys } from 'utils';
import { includes, map } from 'lodash';
import { MessagesItem } from 'admin/schema/Cas';
import { Link } from 'react-router-dom';
interface UserAreaState {
  resetPwdVisible: boolean;
  checkDetailVisible: boolean;
  userDetails: any;
  unreadCount: number;
  messageDrawerVisible: boolean;
  messageList: MessagesItem[];
  messagePagination: {
    current: number;
    pageSize: number;
    total: number;
  };
  messageLoading: boolean;
}
/**个人设置 */
class UserArea extends React.Component<JSONObject, UserAreaState> {
  resetPwdForm: React.RefObject<FormInstance>;

  constructor(prop: {}) {
    super(prop);
    this.resetPwdForm = React.createRef();

    this.state = {
      resetPwdVisible: false,
      checkDetailVisible: false,
      userDetails: {},
      unreadCount: 0,
      messageDrawerVisible: false,
      messageList: [],
      messagePagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      messageLoading: false,
    };
    this.handleResetPwdRequest = this.handleResetPwdRequest.bind(this);
    this.closeResetModal = this.closeResetModal.bind(this);
  }

  componentDidMount(): void {
    this.fetchCasMessagesPoll();
    this.fetchCasMessagesUnreadCount();
  }

  fetchCasMessagesPoll() {
    getCasMessagesPoll()
      .then(res => {
        if (res.status === 200) {
          this.fetchMessageList();
          if (res.data && res.data.hasNew) {
            this.setState({
              unreadCount: res.data.newCount,
            });
          }
        }
      })
      .catch(err => {
        console.error(`轮询消息异常: ${JSON.stringify(err)}`);
        setTimeout(() => {
          this.fetchCasMessagesPoll();
        }, 30000);
      });
  }

  fetchCasMessagesUnreadCount() {
    getCasMessages({ pageNo: 0, pageSize: 1, unreadOnly: false })
      .then(res => {
        if (res.status === 200) {
          this.setState({
            unreadCount: res.data.totalElements,
          });
        }
      })
      .catch(err => {
        console.error(`获取消息异常: ${JSON.stringify(err)}`);
      });
  }
  /**显示个人资料 */
  showDetail = async () => {
    // const webSenstive = await showWebSenstive();
    // const details = webSenstiveMask(this.props.userInfo, webSenstive);
    this.setState({
      checkDetailVisible: true,
      userDetails: this.props.loginInfo,
    });
  };
  /**y隐藏个人资料 */
  closeDetail = () => {
    this.setState({
      checkDetailVisible: false,
      userDetails: {},
    });
  };
  /**显示密码编辑弹窗 */
  showModifyPwd = () => {
    this.setState({
      resetPwdVisible: true,
    });
  };

  /**
   * 发送修改密码请求
   */
  private async handleResetPwdRequest(newPassword: string, oldPassword?: string) {
    try {
      await modifyCasUserPwd({
        id: this.props.loginInfo.id,
        username: this.props.loginInfo.username,
        oldPassword: oldPassword as string,
        confirmPassword: newPassword,
        password: newPassword,
      });
      message.success('密码修改成功');
      this.closeResetModal();
      this.props.setLoginInfo({
        ...this.props.loginInfo,
        changePasswordFlag: false,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }

  /**
   * 关闭重置密码弹窗
   */
  private closeResetModal() {
    this.setState({ resetPwdVisible: false });
  }
  private logout() {
    Modal.confirm({
      content: '确定退出系统吗',
      onOk: async () => {
        // 请求退出登录接口
        try {
          const res = await casLogout();
          if (res.status === 200) {
            console.log('退出系统，点击【确认按钮】---👌👌👌');
            message.warning('正在退出系统');
            logoutSys(true);
          }
        } catch (error) {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        }
      },
    });
  }

  private buildContent() {
    return (
      <>
        <div className="ant-btn-link user-area-item" onClick={this.showDetail}>
          <div className="user-area-container">
            <UserOutlined style={{ fontSize: '25px' }} />
            个人资料 <RightOutlined style={{ fontSize: '25px' }} />
          </div>
        </div>
        <div className="ant-btn-link user-area-item" onClick={this.showModifyPwd}>
          <div className="user-area-container">
            <LockOutlined style={{ fontSize: '25px' }} />
            修改密码 <RightOutlined style={{ fontSize: '25px' }} />
          </div>
        </div>
        <div
          className="ant-btn-link user-area-item"
          onClick={() => {
            this.logout();
          }}
        >
          <div className="user-area-container">
            <LogoutOutlined style={{ fontSize: '25px' }} />
            退出登录 <RightOutlined style={{ fontSize: '25px' }} />
          </div>
        </div>
      </>
    );
  }

  private getRoleNames(arr: any): string {
    if (!arr || !arr.length) return '--';
    return arr
      .map((item: any) => {
        return item.roleName;
      })
      .join(',');
  }

  fetchMessageList() {
    const { current, pageSize } = this.state.messagePagination;
    this.setState({ messageLoading: true });

    getCasMessages({
      pageNo: current - 1,
      pageSize,
      unreadOnly: false,
    })
      .then(res => {
        if (res.status === 200) {
          this.setState({
            messageList: res.data.content,
            messagePagination: {
              ...this.state.messagePagination,
              total: res.data.totalElements,
            },
          });
        }
      })
      .catch(err => {
        console.error(`获取消息列表异常: ${JSON.stringify(err)}`);
      })
      .finally(() => {
        this.setState({ messageLoading: false });
      });
  }

  handleMessageRead(id: string) {
    readCasMessages(id)
      .then(res => {
        if (res.status === 200) {
          this.fetchMessageList();
          this.fetchCasMessagesUnreadCount();
        }
      })
      .catch(err => {
        console.error(`标记已读异常: ${JSON.stringify(err)}`);
      });
  }

  handleMessagePageChange = (page: number, pageSize?: number) => {
    this.setState(
      {
        messagePagination: {
          ...this.state.messagePagination,
          current: page,
          pageSize: pageSize || this.state.messagePagination.pageSize,
        },
      },
      () => {
        this.fetchMessageList();
      }
    );
  };

  toggleMessageDrawer = () => {
    const visible = !this.state.messageDrawerVisible;
    this.setState({
      messageDrawerVisible: visible,
    });
    if (visible) {
      this.fetchMessageList();
    }
  };

  getApproveUrl = business => {
    if (business === '行业短信能力申请') {
      return '/webapp/cas/abilities?activeTab=行业短信';
    }
    if (business === '靶向短信能力申请') {
      return '/webapp/cas/abilities?activeTab=靶向短信';
    }
    if (business === '智能外呼能力申请') {
      return '/webapp/cas/abilities?activeTab=智能外呼';
    }
    if (business === '行业短信签名申请') {
      return '/webapp/cas/signatures?activeTab=industry';
    }
    if (business === '靶向短信签名申请') {
      return '/webapp/cas/signatures?activeTab=target';
    }
    if (business === '智能外呼签名申请') {
      return '/webapp/cas/signatures?activeTab=call';
    }
    if (business === '行业短信模版申请') {
      return '/webapp/cas/templates?activeTab=行业短信';
    }
    if (business === '靶向短信模版申请') {
      return '/webapp/cas/templates?activeTab=靶向短信';
    }
  };

  render() {
    const {
      resetPwdVisible,
      checkDetailVisible,
      userDetails,
      unreadCount,
      messageDrawerVisible,
      messageList,
      messagePagination,
      messageLoading,
    } = this.state;

    return (
      <div className="layout-header-user">
        <Space>
          <Badge count={unreadCount} offset={[-5, 5]} overflowCount={99} style={{ zIndex: 10 }}>
            <Button
              className="layout-user-btn"
              type="primary"
              style={{ padding: '0 8px' }}
              shape="round"
              icon={<BellOutlined />}
              onClick={this.toggleMessageDrawer}
            >
              消息
            </Button>
          </Badge>
          <Popover placement="bottomRight" content={this.buildContent()}>
            <Button
              className="layout-user-btn"
              type="primary"
              style={{ padding: '0 8px' }}
              shape="round"
              icon={<SettingOutlined />}
            >
              个人设置
            </Button>
          </Popover>
        </Space>
        <Modal
          width={650}
          className="user-check-detail"
          title="用户资料"
          visible={checkDetailVisible}
          footer={null}
          destroyOnClose
          onCancel={this.closeDetail}
        >
          <Descriptions column={2}>
            <Descriptions.Item label="账号">{userDetails?.username || '--'}</Descriptions.Item>
            <Descriptions.Item label="昵称">{userDetails?.nickname || '--'}</Descriptions.Item>
            <Descriptions.Item label="单位">{userDetails?.orgName || '--'}</Descriptions.Item>
            <Descriptions.Item label="角色">
              {map(userDetails?.roles, 'name').join(',') || '--'}
            </Descriptions.Item>
            <Descriptions.Item label="手机号">{userDetails?.phone || '--'}</Descriptions.Item>
            <Descriptions.Item label="邮箱">{userDetails?.email || '--'}</Descriptions.Item>
            {/* <Descriptions.Item label="账号">{userDetails?.userName || '--'}</Descriptions.Item>
            <Descriptions.Item label="用户名">{userDetails?.nickName || '--'}</Descriptions.Item>
            <Descriptions.Item label="性别">
              {userDetails?.sex ? '女' : userDetails?.sex === 0 ? '男' : '--'}
            </Descriptions.Item>
            <Descriptions.Item label="企业">{userDetails?.companyName || '--'}</Descriptions.Item>
            <Descriptions.Item label="组织架构">
              {userDetails?.organizationName || '--'}
            </Descriptions.Item>
            <Descriptions.Item label="角色">
              {this.getRoleNames(userDetails.roles)}
            </Descriptions.Item>
            <Descriptions.Item label="手机号">{userDetails?.mobile || '--'}</Descriptions.Item>
            <Descriptions.Item label="身份证号">
              {userDetails?.idCardNumber || '--'}
            </Descriptions.Item>
            <Descriptions.Item label="邮箱">{userDetails?.email || '--'}</Descriptions.Item>
            <Descriptions.Item label="坐席工号">
              {userDetails?.seatsNumber || '--'}
            </Descriptions.Item>
            <Descriptions.Item label="有效期">
              {moment(userDetails.userValidityDate).format('YYYY-MM-DD') || '--'}
            </Descriptions.Item> */}
          </Descriptions>
        </Modal>
        <ResetPassword
          visible={resetPwdVisible}
          submitFn={this.handleResetPwdRequest}
          closeFn={this.closeResetModal}
          forceReset={this.props.loginInfo?.changePasswordFlag}
        />
        <Drawer
          title="消息列表"
          placement="right"
          width={500}
          onClose={this.toggleMessageDrawer}
          visible={messageDrawerVisible}
        >
          <List
            loading={messageLoading}
            dataSource={messageList}
            pagination={{
              current: messagePagination.current,
              pageSize: messagePagination.pageSize,
              total: messagePagination.total,
              onChange: this.handleMessagePageChange,
              simple: true,
            }}
            renderItem={item => (
              <List.Item
                extra={
                  <div>
                    <div>{moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')}</div>
                    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                      {!item.isRead && (
                        <>
                          {includes(
                            [
                              '行业短信能力申请',
                              '靶向短信能力申请',
                              '智能外呼能力申请',
                              '行业短信签名申请',
                              '靶向短信签名申请',
                              '智能外呼签名申请',
                              '行业短信模版申请',
                              '靶向短信模版申请',
                            ],
                            item.business
                          ) && (
                            <Link
                              style={{ padding: '4px 8px' }}
                              to={this.getApproveUrl(item.business)}
                            >
                              审批列表
                            </Link>
                          )}
                          <Button
                            type="link"
                            style={{ padding: '4px 8px' }}
                            onClick={() => this.handleMessageRead(item.id)}
                          >
                            标记已读
                          </Button>
                        </>
                      )}
                    </div>
                  </div>
                }
              >
                <List.Item.Meta title={item.title} description={item.content} />
              </List.Item>
            )}
          />
        </Drawer>
      </div>
    );
  }
}

// state 注入props
const mapStateToProps = (state: JSONObject) => {
  return {
    token: state.token,
    loginInfo: state.loginInfo,
    userInfo: state.userInfo,
  };
};
// action 注入props
const mapDispatchToProps = {
  setToken,
  setUserInfoLater,
  setLoginInfo,
  setUserInfo,
  setCheckInState,
  setUaConfig,
  setAddTaskFormData,
};

export default connect(mapStateToProps, mapDispatchToProps)(UserArea);
